package com.lu.manage.modular.system.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lu.manage.core.common.constant.SystemConstant;
import com.lu.manage.core.common.enums.YesOrNotEnum;
import com.lu.manage.core.common.exception.SysLogExcepetion;
import com.lu.manage.core.schedue.quartz.schedule.QuartzManage;
import com.lu.manage.core.schedue.quartz.schedule.ScheduleJob;
import com.lu.manage.core.schedue.quartz.utils.ScheduleJobUtils;
import com.lu.manage.core.tips.SuccessTip;
import com.lu.manage.core.utils.StringUtil;
import com.lu.manage.core.utils.ToolUtil;
import com.lu.manage.modular.system.mapper.TaskMapper;
import com.lu.manage.modular.system.model.Task;
import com.lu.manage.modular.system.service.TaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Project sKnowledge-Blog
 * @Author: zhanglu
 * @Date: 2019-11-15 10:41:48
 * @Description: 系统任务表 服务实现类
 */
@Service
public class TaskServiceImpl extends ServiceImpl<TaskMapper, Task> implements TaskService {

    @Autowired
    private QuartzManage quartzManage;

    @Override
    public Object listPage(Map<String, Object> map) throws SysLogExcepetion {
        SuccessTip successTip = new SuccessTip();
        try {
            Page page = new Page(Integer.valueOf((String)map.get(SystemConstant.PAGE)), Integer.valueOf((String)map.get(SystemConstant.LIMIT)));
            QueryWrapper queryWrapper = new QueryWrapper();
            map.forEach((k, v) -> {
                if(!k.equals(SystemConstant.PAGE) && !k.equals(SystemConstant.LIMIT)){
                    if(k.equals(SystemConstant.SEARCH_WORDS)){
                        queryWrapper.like("job_name", v);
                    }else {
                        queryWrapper.eq(k, v);
                    }
                }
            });
            IPage<Task> taskList = this.baseMapper.selectPage(page, queryWrapper);
            taskList.getRecords().stream().forEach(o -> {

                quartzManage.getRunningJob().stream().forEach(o1 -> {

                    if(o.getJobName().equals(o1.getJobName())){
                        o.setState(2);
                        return;
                    }

                });

            });
            successTip.setCount(taskList.getTotal());
            successTip.setData(taskList.getRecords());
        } catch (Exception e) {
            throw new SysLogExcepetion(Thread.currentThread(), e);
        }
        return successTip;
    }

    @Override
    public Object list(Map<String, Object> map) throws SysLogExcepetion{
        List<Task> taskList = null;
        try {
            taskList = new ArrayList<>();
            QueryWrapper<Task> queryWrapper = new QueryWrapper<>();
            if(ToolUtil.isNotEmpty(map)){
                map.forEach((k, v) -> {
                    queryWrapper.eq(k, v);
                });
            }
            taskList = this.baseMapper.selectList(queryWrapper);
        } catch (Exception e) {
            throw new SysLogExcepetion(Thread.currentThread(), e);
        }
        return taskList;
    }

    @Override
    public Object addObj(Task task) throws SysLogExcepetion{
        try {
            task.setJobName(System.currentTimeMillis() + StringUtil.getRandomStr(3));
            this.baseMapper.insert(task);
            quartzManage.addJob(ScheduleJobUtils.entityToData(task));
            return this.baseMapper.insert(task);
        } catch (Exception e) {
            throw new SysLogExcepetion(Thread.currentThread(), e);
        }
    }

    @Override
    public Object updateObj(Task task) throws SysLogExcepetion{
        try {
            this.baseMapper.updateById(task);
            if(ToolUtil.isNotEmpty(task.getId())){
                quartzManage.deletejob(ScheduleJobUtils.entityToData(task));
                quartzManage.addJob(ScheduleJobUtils.entityToData(task));
            }
            return this.baseMapper.updateById(task);
        } catch (Exception e) {
            throw new SysLogExcepetion(Thread.currentThread(), e);
        }
    }

    @Override
    public Object deleteObj(String data) throws SysLogExcepetion{
        try {
            List<Task> taskList = JSONArray.parseArray(data, Task.class);
            List<String> ids = taskList.stream().map(Task::getId).collect(Collectors.toList());
            if(ToolUtil.isNotEmpty(ids)){
                this.baseMapper.deleteBatchIds(ids);
            }
            for (Task task : taskList) {
                quartzManage.deletejob(ScheduleJobUtils.entityToData(task));
            }
            return new SuccessTip();
        } catch (Exception e) {
            throw new SysLogExcepetion(Thread.currentThread(), e);
        }
    }

    @Override
    public void scheduleJobInitListener() throws SysLogExcepetion {
        try {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("state", YesOrNotEnum.Y.getCode());
            List<Task> quartzTaskList = this.baseMapper.selectList(queryWrapper);
            if(quartzTaskList != null){
                for (Task quartzTask : quartzTaskList) {
                    ScheduleJob scheduleJob = ScheduleJobUtils.entityToData(quartzTask);
                    quartzManage.addJob(scheduleJob);
                }
            }
        } catch (Exception e) {
            throw new SysLogExcepetion(Thread.currentThread(), e);
        }
    }

}
